import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'

// 异步数据
const getList = () => {
  return new Promise((resolve, reject) => {
    const defaultList = [
      { id: 1, title: '开会1', desc: 'xxx', date: '2020-12-12', isDone: true },
      { id: 2, title: '开会2', desc: 'xxx', date: '2020-12-14', isDone: false }
    ]
    setTimeout(() => {
      resolve(defaultList)
    }, 100)
  })
}
export default createStore({
  state: {
    list: []
  },
  mutations: {
    setList (state, payload) {
      state.list = payload
    },
    addItem (state, todo) {
      let id = 1
      const length = state.list.length
      if (length) {
        id = state.list[length - 1].id + 1
      }
      state.list.push({ ...todo, id })
    }
  },
  actions: {
    add (context, todo) {
      context.commit('addItem', todo)
    },
    getList (context) {
      if (context.state.list.length) {
        return context.state.list
      } else {
        return getList().then(res => {
          context.commit('setList', res)
          console.log('res', res)
          return res
        })
      }
    }
  },
  modules: {
  },
  plugins: [createPersistedState()]
})
